package crm8000.services

import org.springframework.web.context.request.RequestContextHolder;

import crm8000.Models.User;
import crm8000.helper.Result
import grails.transaction.Transactional

@Transactional
class UserService {

    def doLogin(String loginName, String password) {
		def user = User.findByLoginNameAndPassword(loginName, password.encodeAsMD5())
		
		if (user) {
			this.session.loginUserId = user.userId
			this.session.loginUserName = user.name
			return new Result(success: true)
		} else {
			return new Result(success: false, msg: "用户名或者密码错误")
		}
    }
	
	def getSession(){
		RequestContextHolder.currentRequestAttributes().getSession()
	}
	
	def getLoginUserName() {
		return this.session.loginUserName
	}
	
	def getLoginUserId() {
		return this.session.loginUserId
	}
	
	def clearLoginUserInSession() {
		this.session.loginUserId = null
		this.session.loginUserName = null
	}
	
	def changeMyPassword(String userId, String oldPassword, String newPassword) {
		if (this.loginUserId != userId) {
			return new Result(success: false, msg: "当前用户Session失效，请重新登录系统")	
		}
		
		def user = User.findByUserIdAndPassword(userId, oldPassword.encodeAsMD5())
		
		if (!user) {
			return new Result(success: false, msg: "旧密码错误")
		}
		
		user.password = newPassword.encodeAsMD5()
		user.save()
		
		return new Result(success: true)
	}
}
